| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 
 | 
 
 print("切片-------------")
 
 a=['aaa','bbb','ccc','ddd']
 print(a)
 print(a[:3])
 print(a[1:3])
 print(a[-2:])
 print(a[-3:-1])
 L=list(range(30))
 print(L)
 print(L[:10:2])
 print(L[:])
 
 print((0,1,2,3,4,5,6)[:3])
 print("abcdefg"[::2])
 
 print("利用切片,实现trim()-------------")
 def trim(s):
 if len(s)==0:
 return s
 if s[0]==' ':
 return trim(s[1:])
 if s[-1]==' ':
 return trim(s[:-1])
 else:
 return s
 
 if trim('hello  ') != 'hello':
 print('测试失败!')
 elif trim('  hello') != 'hello':
 print('测试失败!')
 elif trim('  hello  ') != 'hello':
 print('测试失败!')
 elif trim('  hello  world  ') != 'hello  world':
 print('测试失败!')
 elif trim('') != '':
 print('测试失败!')
 elif trim('    ') != '':
 print('测试失败!')
 else:
 print('测试成功!')
 
 print("判断是否可以迭代-------------")
 from collections import Iterable
 print(isinstance('abcd',Iterable))
 print(isinstance([1,2,3,4],Iterable))
 print(isinstance((1,2,3,4),Iterable))
 
 print("enumerate实现下标循环-------------")
 for i,value in enumerate([1,2,3,4]):
 print(i,value)
 
 print("使用两个变量迭代-------------")
 for x,y in ((1,1),(2,2),(3,3)):
 print(x,y)
 
 print("列表生成式-------------")
 
 print([x*x for x in range(1,11)])
 print([x * x for x in range(1,11) if x%2 == 0])
 
 print([m+n for m in'abc' for n in 'xyz'])
 
 import os
 print([d for d in os.listdir('.')])
 
 L=['Hello','World','IBM','Apple']
 print([s.lower() for s in L])
 
 L1 = ['Hello', 'World', 18, 'Apple', None]
 L2 = [s.lower() for s in L1 if isinstance(s, str)]
 print(L1)
 print(L2)
 if L2 == ['hello', 'world', 'apple']:
 print('测试通过!')
 else:
 print('测试失败!')
 
 print("生成器-------------")
 g=(x*x for x in range(10))
 print('next(g):')
 next(g)
 next(g)
 next(g)
 
 
 print('斐波那契数列')
 def fib(max):
 n,a,b = 0,0,1
 while n<max:
 yield b
 a,b=b,a+b
 n=n+1
 return 'done'
 
 f=fib(9)
 
 for x in f:
 print(x)
 
 
 while True:
 try:
 x=next(f)
 print('g:',x)
 except StopIteration as e:
 print('Generator return value:',e.value)
 break
 
 
 def triangles():
 l=[1]
 while True:
 yield l
 l=[0]+l+[0]
 l=[l[i]+l[i+1] for i in range(len(l)-1)]
 
 t=triangles()
 for i in range(7):
 print(next(t))
 
 
 from collections import Iterator
 from collections import Iterable
 print(isinstance([],Iterator))
 print(isinstance([],Iterable))
 
 |